﻿using CodeLabs.Util;
using Composr.Core;
using Composr.Core.Repositories;
using Composr.Core.Services;
using System;
using System.Text;

namespace Composr.Services
{
    public class BlogService : Service<Blog>
    {
        private const string blogkey = "Blog_";
        public BlogService(BlogRepository repository) : base(repository) { }        

        public override void Validate(Blog blog)
        {
            StringBuilder exceptions = new StringBuilder(100);
            
            if (blog==null) throw new ComposrException("blog must not be null");

            exceptions.Append(CheckBlogName(blog) + Environment.NewLine);
            if(!exceptions.ToString().Replace(Environment.NewLine, string.Empty).IsBlank())
            {
                throw new ComposrException(exceptions.ToString());
            }
        }

        private string CheckBlogName(Blog blog)
        {
            if(blog.Name.IsBlank())
            {
                return "blog name must not be empty";
            }
            return null;
        }

        private string CheckNull(Blog blog)
        {
            if (blog == null) return "blog must not be null";
            return null;
        }

        public override string GetCacheKey(int id)
        {
            return blogkey + id.ToString();
        }

        public override string GetCacheKey(Blog blog)
        {
            if (blog.BlogID.HasValue) return GetCacheKey(blog.BlogID.Value);
            else if (!blog.Name.IsBlank()) return blogkey + blog.Name;

            return null;
        }
    }
}
